#include <os/lock.h>
#include <os/sched.h>
#include <atomic.h>
#include <mthread.h>
void spin_lock_init(spin_lock_t *lock)
{
    /* TODO */
}

int spin_lock_try_acquire(spin_lock_t *lock)
{
    /* TODO */
}

void spin_lock_acquire(spin_lock_t *lock)
{
    /* TODO */
}

void spin_lock_release(spin_lock_t *lock)
{
    /* TODO */
}

void do_mutex_lock_init(mutex_lock_t *lock)
{
    /* TODO */
    if(lock->lock.status==LOCKED)
    	return ;
    if(lock->block_queue.next!=&lock->block_queue)
    init_list_head(&lock->block_queue);
    lock->lock.status=UNLOCKED;
}

void do_mutex_lock_acquire(mutex_lock_t *lock)
{
    /* TODO */
    if(lock->lock.status==LOCKED)
    	{do_block(&current_running->list,&lock->block_queue);
    	lock->lock.status=LOCKED;}
	else
	lock->lock.status=LOCKED;
}

void do_mutex_lock_release(mutex_lock_t *lock)
{
    /* TODO */
    if(lock->lock.status==LOCKED){
    //while(lock->block_queue.next!=&lock->block_queue)
    if(lock->block_queue.next!=&lock->block_queue)
    do_unblock(lock->block_queue.next);
	lock->lock.status=UNLOCKED;}
}
void do_mutex_lock_destroy(mutex_lock_t *lock){
    lock->block_queue.next=(void*)0;
}

int do_cond_init(mthread_cond_t *cond)
{
    // TODO:
    cond->num_waiting=0;
    init_list_head(&cond->wait_queue);
    return 1;
}
int do_cond_destroy(mthread_cond_t *cond) {
    // TODO:
    cond->num_waiting=0;
    init_list_head(&cond->wait_queue);
    return 1;
}
int do_cond_wait(mthread_cond_t *cond, mthread_mutex_t *mutex)
{
    // TODO:
    cond->num_waiting++;
    list_add_tail(&current_running->list,&cond->wait_queue);
    current_running->status=TASK_BLOCKED;
    do_mutex_lock_release(&mutex);
    do_scheduler();
    do_mutex_lock_acquire(&mutex);
    return 0;
}
int do_cond_signal(mthread_cond_t *cond)//释放一个
{
    // TODO:
    if(cond->num_waiting>0){
        list_del(cond->wait_queue.next);
        list_add_tail(cond->wait_queue.next,&cond->wait_queue);
        list_entry(cond->wait_queue.next,pcb_t,list)->status=TASK_READY;
        cond->num_waiting--;
    }
    return 0;
}
int do_cond_broadcast(mthread_cond_t *cond)//释放全部
{
    // TODO:
    if(cond->num_waiting>0){
        do_unblock_all(cond->wait_queue);
        cond->num_waiting=0;
    }
    return 0;
}    
int do_barrier_init(mthread_barrier_t * barrier, unsigned count)
{
    // TODO:
   
}
int do_barrier_wait(mthread_barrier_t *barrier)
{
    // TODO:
   
}
int do_barrier_destroy(mthread_barrier_t *barrier)
{
    // TODO:
    
}